package cn.shengchao.examstar.ai.application.service;

import cn.shengchao.examstar.ai.infrastructure.external.ai.service.res.KnowledgePointDescriptionDTO;
import cn.shengchao.examstar.shared.application.ai.AiKnowledgeSharedService;
import cn.shengchao.examstar.shared.domain.ai.dto.KnowledgePointDescriptionSharedDTO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * AI知识点共享服务实现
 * 实现共享接口，提供跨模块的AI知识点服务能力
 * 
 * @author examstar
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class AiKnowledgeSharedServiceImpl implements AiKnowledgeSharedService {

    private final AiKnowledgeService aiKnowledgeService;
    
    @Override
    public KnowledgePointDescriptionSharedDTO generateKnowledgeDescription(
            Long userId, 
            String knowledgePointName,String subject) {
        
        try {
            // 调用内部服务
            KnowledgePointDescriptionDTO result = aiKnowledgeService.generateKnowledgeDescription(
                    userId, knowledgePointName,subject);
            
            // 转换为共享DTO
            List<KnowledgePointDescriptionSharedDTO.LearningTip> tips = new ArrayList<>();
            if (result.getLearningSuggestions() != null) {
                tips = result.getLearningSuggestions().stream()
                        .map(tip -> new KnowledgePointDescriptionSharedDTO.LearningTip(tip.getTip()))
                        .collect(Collectors.toList());
            }
            
            // 生成HTML格式的学习建议
            String learningSuggestionsHtml = tips.stream()
                    .map(tip -> "<li>" + tip.getTip() + "</li>")
                    .collect(Collectors.joining("", "<ul>", "</ul>"));
            
            return KnowledgePointDescriptionSharedDTO.builder()
                    .coreConcept(result.getCoreConcept())
                    .keyPoints(result.getKeyPoints())
                    .learningSuggestions(learningSuggestionsHtml)
                    .learningSuggestionList(tips)
                    .build();
            
        } catch (IOException e) {
            log.error("生成知识点描述失败", e);
            // 出错时返回带有错误信息的默认对象
            return KnowledgePointDescriptionSharedDTO.builder()
                    .coreConcept("")
                    .keyPoints("")
                    .learningSuggestions("")
                    .build();
        }
    }
} 